package com.thinktank.controller;

import static com.thinktank.util.DbUtil.*;

import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.oreilly.servlet.*;
import com.oreilly.servlet.multipart.*;
import com.thinktank.vo.*;
import com.thinktank.dao.*;

public class BoardRegProcessController implements Controller {
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 파일 업로드 기본 세팅
		ServletContext sc = request.getServletContext();
		String path = sc.getRealPath("\\upload");
		String encType = "utf-8";
		int maxSize = 5 * 1024 * 1024;
		File targetDir = new File(path);
		if (!targetDir.exists())
			targetDir.mkdirs();

		request.setCharacterEncoding("utf-8");

		MultipartRequest multi = new MultipartRequest(request, path, maxSize,
				encType, new DefaultFileRenamePolicy());
		// 게시판 글 등재
		String bSubject = multi.getParameter("bSubject");
		String bContent = multi.getParameter("bContent");
		String bCategory = multi.getParameter("category");
		String bWriter = multi.getParameter("bWriter");
		bContent = bContent.replaceAll("\r\n", "<br />");
		
		Board board = new Board();
		board.setbSubject(bSubject);
		board.setbContent(bContent);
		board.setbCategory(bCategory);
		board.setbWriter(bWriter);
		
		Connection con = getConnection();
		BoardDao dao = new BoardDao(con);
		
		int bNo = dao.insert(board);
		
		int result = 0;
		// 파일 첨부
		Enumeration files = multi.getFileNames();
		
		while (files.hasMoreElements()) {
			String formName = (String) files.nextElement();
			String fileName = multi.getFilesystemName(formName);
			String originalFileName = multi.getOriginalFileName(formName);
			
			// 이미지 파일이면
			
			if(originalFileName!=null && originalFileName.endsWith("jpg")){
				Album a = new Album();
				
				a.setNo(bNo+"");
				a.setLoc(multi.getParameter("loc"));
				a.setTag(multi.getParameter("tag"));
				a.setSrc(originalFileName);
				a.setPath(fileName);
				
				AlbumDao dao2 = new AlbumDao(con);
				result = dao2.insert(a);
			}
			
		}

		close(con);


		

		if (result == 0 && bNo == 0) {
			return "error.jsp";
		}

		return "redirect:board.do";

	}
}